package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.Student;

public class Studentdao {
	private Student stu;

	public void Inserts(Student stu) {
		Connection conn = DBUtil.getConn();
		String sql = "insert into student(name,sex) values(?,?)";
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stu.getName());
			ps.setString(2, stu.getSex());
			ps.executeQuery();
			System.out.println("学生信息录入成功！");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void Delete(Student stu) {
		Connection conn = DBUtil.getConn();
		String sql = "delete from student where id=?";
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			pstm.setInt(1, stu.getId());
			pstm.executeQuery();
			System.out.println("学生信息删除成功！");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<Student> selAll() {
		List<Student> stus = new ArrayList<>();
		Connection conn = DBUtil.getConn();
		String sql = "select * from student";
		try {
			Statement stm = conn.createStatement();

			ResultSet rs = stm.executeQuery(sql);

			while (rs.next()) {
				stu = new Student();
				stu.setId(rs.getInt("id"));
				stu.setName(rs.getString("name"));
				stu.setSex(rs.getString("sex"));
				stus.add(stu);
			}
			return stus;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

	}

	public Student selOne(int id) {
		stu = new Student();
		String sql = "select * from student where id=?";
		try {
			PreparedStatement ps = DBUtil.getConn().prepareStatement(sql);
			stu = new Student();
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			rs.next();

			stu.setId(rs.getInt("id"));
			stu.setName(rs.getString("name"));
			stu.setSex(rs.getString("sex"));
			
			return stu;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

	}

	public void updStu(){
		String sql="update student set name=?,sex=? where id=?";
		try {
			PreparedStatement ps=DBUtil.getConn().prepareStatement(sql);
			
			ps.setString(1, stu.getName());
			ps.setString(2, stu.getSex());
			ps.setInt(3, stu.getId());
			ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
